package com.gzhryc.shared_device.pcl.code.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.pcl.code.dao.PCLFeeTemplateDao;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLFeeTemplate;
import com.gzhryc.shared_device.pcl.code.dao.enums.PCLFeeTemplateEnum;
import com.gzhryc.shared_device.pcl.code.services.dto.PCLFeeTemplateSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class PCLFeeTemplateService {

    static Logger log = Logger.getLogger(PCLFeeTemplateService.class);

    public static PCLFeeTemplateService self() {
        return MultiDBTools.getService(PCLFeeTemplateService.class, true);
    }

    public static PCLFeeTemplateService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, PCLFeeTemplateService.class, true);
    }

    PCLFeeTemplateDao dao;

    public PCLFeeTemplateService(String jdbcKey) {
        dao = new PCLFeeTemplateDao(jdbcKey);
    }

    public List<PCLFeeTemplate> findJoinBySearch(PCLFeeTemplateSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        if(search.getType() != null){
            if(search.getType().equals(1)) {
                conditions.and().is("userId",0);
            }else if(search.getType().equals(2)){
                conditions.and().not("userId",0);
            }
        }
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(PCLFeeTemplateSearch search){
        Conditions conditions = dao.buildConditions(search);
        if(search.getType() != null){
            if(search.getType().equals(1)) {
                conditions.and().is("userId",0);
            }else if(search.getType().equals(2)){
                conditions.and().not("userId",0);
            }
        }
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public List<PCLFeeTemplate> findJoinDefPlatform(){
        Conditions conditions = new Conditions(PCLFeeTemplate.class);
        conditions.and().is("userId",0);
        conditions.and().is("state", PCLFeeTemplateEnum.State.Default.index());
        try {
            return dao.findJoinByCondition(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<PCLFeeTemplate> findJsonByIds(List<Long> feeTemplateIds){
        Conditions conditions = new Conditions(PCLFeeTemplate.class);
        conditions.and().in("id",feeTemplateIds);
        try {
            return dao.findJoinByCondition(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<PCLFeeTemplate> findByUserId(Long userId) {
        if (userId != null) {
            Conditions conditions = new Conditions(PCLFeeTemplate.class);
            conditions.and().is("userId", userId);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public List<PCLFeeTemplate> findJoinByDeviceTypeId(String deviceTypeId) {
        if(StringTools.isNotBlank(deviceTypeId)){
            Conditions conditions = new Conditions(PCLFeeTemplate.class);
            conditions.and().is("deviceTypeId", deviceTypeId);

            try {
                return dao.findJoinByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public List<PCLFeeTemplate> findByUserIdAndDeviceTypeId(Long userId,String deviceTypeId) {
        if (userId != null && StringTools.isNotBlank(deviceTypeId)) {
            Conditions conditions = new Conditions(PCLFeeTemplate.class);
            conditions.and().is("userId", userId);
            conditions.and().is("deviceTypeId",deviceTypeId);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public PCLFeeTemplate getById(Long id) {
        if(id != null) {
            try {
                return dao.getById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public PCLFeeTemplate getDefPlatformByDeviceTypeId(String deviceTypeId){
        if(StringTools.isNotBlank(deviceTypeId)){
            Conditions conditions = new Conditions(PCLFeeTemplate.class);
            conditions.and().is("userId",0);
            conditions.and().is("deviceTypeId",deviceTypeId);
            conditions.and().is("state",PCLFeeTemplateEnum.State.Default.index());

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public PCLFeeTemplate getDefByUserIdAndDeviceTypeId(Long userId,String deviceTypeId){
        if(userId != null && StringTools.isNotBlank(deviceTypeId)){
            Conditions conditions = new Conditions(PCLFeeTemplate.class);
            conditions.and().is("userId",userId);
            conditions.and().is("deviceTypeId",deviceTypeId);
            conditions.and().is("state",PCLFeeTemplateEnum.State.Default.index());

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public PCLFeeTemplate getNewByKeys(Long userId,String deviceTypeId) {
        if(userId != null && StringTools.isNotBlank(deviceTypeId)) {
            Conditions conditions = new Conditions(PCLFeeTemplate.class);
            conditions.and().is("userId",userId);
            conditions.and().is("deviceTypeId",deviceTypeId);
            conditions.desc("createDate");
            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public PCLFeeTemplate getJoinById(Long id) {
        if(id != null) {
            try {
                return dao.getJoinById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public boolean add(PCLFeeTemplate feeTemplate)throws LogicException {
        if(feeTemplate.getUserId() == null){
            feeTemplate.setUserId(0L);  //不设置则是平台模版
        }
        PCLFeeTemplate temp = null;
        if(feeTemplate.getUserId() == 0) {
            temp = getDefPlatformByDeviceTypeId(feeTemplate.getDeviceTypeId());
        }else {
            temp = getDefByUserIdAndDeviceTypeId(feeTemplate.getUserId(),feeTemplate.getDeviceTypeId());
        }

        if(temp != null){
            feeTemplate.setState(PCLFeeTemplateEnum.State.Normal.index());
        }else{
            feeTemplate.setState(PCLFeeTemplateEnum.State.Default.index());
        }
        feeTemplate.setCreateDate(new Date());
        try {
            return dao.insert(feeTemplate) > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean setDefState(Long id) throws LogicException {
        PCLFeeTemplate feeTemplate = getById(id);
        if(feeTemplate == null){
            throw new LogicException("未找到收费模版");
        }
        PCLFeeTemplate temp = null;
        if(feeTemplate.getUserId() == 0) {
            temp = getDefPlatformByDeviceTypeId(feeTemplate.getDeviceTypeId());
        }else {
            temp = getDefByUserIdAndDeviceTypeId(feeTemplate.getUserId(),feeTemplate.getDeviceTypeId());
        }

        if(temp != null){
            if(temp.getId().equals(id)) {
                return true;
            }else{
                JdbcSession.begin();
                try{
                    PCLFeeTemplate updateEntity = new PCLFeeTemplate();
                    updateEntity.setId(temp.getId());
                    updateEntity.setState(PCLFeeTemplateEnum.State.Normal.index());

                    PCLFeeTemplate updateEntity1 = new PCLFeeTemplate();
                    updateEntity1.setId(id);
                    updateEntity1.setState(PCLFeeTemplateEnum.State.Default.index());

                    if(dao.updateNotNull(updateEntity) > 0){
                        if(dao.updateNotNull(updateEntity1) > 0){
                            JdbcSession.commit();
                            return true;
                        }
                    }
                }catch (SQLException e){
                    log.error(e.getMessage(),e);
                }finally {
                    JdbcSession.end();
                }
            }
        }else{
            PCLFeeTemplate updateEntity = new PCLFeeTemplate();
            updateEntity.setId(id);
            updateEntity.setState(PCLFeeTemplateEnum.State.Default.index());

            try {
                return dao.updateNotNull(updateEntity) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean updateNotNull(PCLFeeTemplate feeTemplate) throws LogicException {
        feeTemplate.setState(null);     //不对状态进行修改
        try {
            return dao.updateNotNull(feeTemplate) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public boolean deleteById(Long id)throws LogicException{
        try {
            return dao.deleteById(id) >0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }
}
